package com.shengyijie.activity.share;
      

import org.apache.http.HttpResponse; 

import weibo4android.OAuthConstant;
import weibo4android.Weibo; 
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
    
import com.shengyijie.activity.R;     
import com.shengyijie.activity.commen.ItemListActivity;
import com.shengyijie.adapter.view.AlertBox;
import com.shengyijie.adapter.view.AlertBox.OnCanceledListener;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.baseobject.RenrenData; 
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.Configuration;
import com.tencent.weibo.utils.OAuthClient;

import android.app.Activity;  
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent; 
import android.content.DialogInterface.OnKeyListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; 
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window; 
import android.view.View.OnClickListener;
import android.widget.Button;  
import android.widget.TextView;
import android.widget.Toast;
public class ShareSelectActivity extends Activity implements OnClickListener{
  
	 private Button sina;
	 private Button renren;
	 private Button tencent;
	 private Button message;
	 private Button email;
	 
	 public Task task;
	 
	 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
        setContentView(R.layout.shareselect);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,      // 注意顺序
                R.layout.title);
         
        initView();
     }
	 
	 public void initView(){
		 Button back = (Button) this.findViewById(R.id.back);
		 back.setVisibility(View.VISIBLE);
		 back.setOnClickListener(this);	
         TextView tv = (TextView) this.findViewById(R.id.title); 
         tv.setText("分享信息"); 
          
		 renren=(Button) this.findViewById(R.id.renren);
		 renren.setOnClickListener(this);
		 
		 sina=(Button) this.findViewById(R.id.sina);
		 sina.setOnClickListener(this);
		 
		 tencent=(Button) this.findViewById(R.id.tencent);
		 tencent.setOnClickListener(this);
		 
		 message=(Button) this.findViewById(R.id.message);
		 message.setOnClickListener(this);
		 
		 email=(Button) this.findViewById(R.id.email);
		 email.setOnClickListener(this);
	 	  
         mypDialog=new AlertBox(ShareSelectActivity.this,ShareSelectActivity.this,findViewById(R.id.share)); 
         mypDialog.setCompletedListener(new OnCanceledListener(){ 
				@Override
				public void onCanceled() { 
					if(task.getStatus()==AsyncTask.Status.RUNNING){
			    		 task.cancel(true); 
					  }
				}});
	 }
	 
	 
	  
		
	@Override
	public void onClick(View v) { 
		switch(v.getId()){
		   case R.id.sina: 
			   ShareConstant.share_type=ShareConstant.SHARE_SINA;
			   openSinaweiboOauthPage();
			  break;
		   case R.id.renren:  
			   ShareConstant.share_type=ShareConstant.SHARE_RENREN;
			   openRenrenOauthPage();
			  break;
		   case R.id.tencent:  
			   ShareConstant.share_type=ShareConstant.SHARE_TENCNT;
			   qqOauth();
			  break; 
		   case R.id.message:  
			   sendMessage();
			  break; 
		   case R.id.email:  
			   sendEmail();
			  break; 
		   case R.id.back:  
			   this.finish();
			  break; 
		}
	}  
	
	public void sendMessage(){
		Intent it = new Intent(Intent.ACTION_VIEW);   
		it.putExtra("sms_body",ContextApplication.shareContent);   
    	it.setType("vnd.android-dir/mms-sms");   
    	ShareSelectActivity.this.startActivityForResult(it,2); 
	}
	
	public void sendEmail(){
		 Intent it = new Intent(Intent.ACTION_SEND);  
		   it.putExtra(Intent.EXTRA_EMAIL, "");  
		    it.putExtra(Intent.EXTRA_TEXT, ContextApplication.shareContent);  
		    it.setType("text/plain");  
		    startActivity(Intent.createChooser(it, "Choose Email Client"));
	}
	public void openSinaweiboOauthPage(){ 
		try { 
		   String[] oauth_token_array = TokenStore.fetch(this,ShareConstant.share_type);
		   ShareConstant.token = oauth_token_array[0];
		   ShareConstant.tokenSecret= oauth_token_array[1];
		   if(ShareConstant.token != null && ShareConstant.tokenSecret != null){
			    Intent i=new Intent();
		        i.setClass(this, ShareDialog.class);
		        this.startActivityForResult(i, 3);
		   }else{
			    System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
				System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
			    task=new Task();
			    task.execute(TASK_OAUTH_SINA); 
		   }
		} catch (Exception e) {}
		    
		    
	}
	String url="";
	public String getSinaRequestToken(){
		String result="fail";
		try{
	        Weibo weibo = new Weibo();
	        RequestToken requestToken; 
			requestToken =weibo.getOAuthRequestToken("weibo4android://OAuthActivity");
		    OAuthConstant.getInstance().setRequestToken(requestToken);
			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&display=mobile"); 
			url=uri.toString();
			if(requestToken!=null&&
					requestToken.getToken().length()>5&&
					requestToken.getTokenSecret().length()>5){
				result="sina_success";
			}
		}catch(Exception e){}
		return result;
	}
	
	public String getTencentRequestToken(){
		String result="fail";
		try{
			oauth = auth.requestToken(oauth); 
			if (oauth.getStatus() == 1) {
				result="fail";
			} else {
				String oauth_token = oauth.getOauth_token(); 
				url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="
					+ oauth_token;
				result="tencent_success"; 
			} 
		}catch(Exception e){}
		return result;
	}
	
	public void openRenrenOauthPage(){ 
		try {
			
			   String[] oauth_token_array = TokenStore.fetch(this,ShareConstant.share_type);
			   ShareConstant.token = oauth_token_array[0];
			   ShareConstant.tokenSecret= oauth_token_array[1];
			   if(ShareConstant.token != null && ShareConstant.tokenSecret != null){
				    Intent i=new Intent();
			        i.setClass(this, ShareDialog.class);
			        this.startActivityForResult(i, 3);
			   }else{
				   String url="https://graph.renren.com/oauth/authorize?" +
				    		"client_id="+ShareConstant.RENREN_API_KEY +
				    		"&redirect_uri=http://graph.renren.com/oauth/login_success.html" +
				    		"&response_type=code" +
				    		"&scope=status_update" +
				    		"&response_type=code" +
				    		"&display=mobile";
				    Intent i=new Intent();
				    i.putExtra("uri", url);
				    i.putExtra("type", ShareConstant.share_type);
				    i.setClass(this, ShareLogin.class);
				    this.startActivityForResult(i, 1);
			   }
			    
		} catch (Exception e) {}
}
	 
    
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		   
		 if(requestCode==3){
				if (resultCode != RESULT_OK) {
					return;
				}
			   try{
			       String state = data.getStringExtra("state");
			       if(state.equals("exit")){
			    	   Bundle bd = new Bundle();
			           bd.putString("state", "exit");	
			           Intent it = new Intent();
			           it.putExtras(bd);
			           setResult(RESULT_OK, it); 
			    	   this.finish();
			       }
			   }
			   catch(Exception e){}
		   }
		 if(requestCode==1){
				if (resultCode != RESULT_OK) {
					return;
				} 
			       String token = data.getStringExtra("token");
			       String oauth_verifier = data.getStringExtra("oauth_verifier");
			       String state = data.getStringExtra("state");
			       int type = data.getIntExtra("type", 1); 
			       if(type==ShareConstant.SHARE_SINA){ 
			    	    try {
							RequestToken requestToken= OAuthConstant.getInstance().getRequestToken();
							AccessToken accessToken=requestToken.getAccessToken(token);
							ShareConstant.token = accessToken.getToken();
							ShareConstant.tokenSecret= accessToken.getTokenSecret();
							TokenStore.store(this, ShareConstant.SHARE_SINA, accessToken.getToken(),
									accessToken.getTokenSecret());
//							OAuthConstant.getInstance().setAccessToken(accessToken);  
					        Intent i=new Intent();
					        i.setClass(this, ShareDialog.class);
					        this.startActivityForResult(i, 3);
			    	    }catch (Exception e){}
			       } else if(type==ShareConstant.SHARE_RENREN){
			    	   
			    	   try{
						   RenrenData renrenData = null; 
					       if(state.equals("ok")){
					    	   HttpConnectApi httpConnect=HttpConnectApi.getInstance();
					           try {
					               HttpResponse response=httpConnect.getRenren(token);
					               if (response.getStatusLine().getStatusCode() == 200)
					   			   {           	
					              	    JsonParser jsonParser=JsonParser.getInstance();
					              	    renrenData=jsonParser.getRenrenData(response);	
					              	    ShareConstant.token = renrenData.getSession_key();
										ShareConstant.tokenSecret= renrenData.getSession_key();
							   			TokenStore.store(this, ShareConstant.SHARE_RENREN, renrenData.getSession_key(),
							   					renrenData.getSession_key());
						                Intent i=new Intent();
								        i.setClass(this, ShareDialog.class);
								        this.startActivityForResult(i, 3);
				                        Toast.makeText(this, "人人网登录认证成功", Toast.LENGTH_LONG).show();
					   			   } 
					                
					           }catch (Exception e) {
					        	   Toast.makeText(this, "人人网登录失败", Toast.LENGTH_LONG).show();
					           } 
					       }else{
					    	   Toast.makeText(this, "人人网登录失败", Toast.LENGTH_LONG).show();
					       }
					   }
					   catch(Exception e){}
			       }  else if(type==ShareConstant.SHARE_TENCNT){ 
				   		oauth.setOauth_verifier(oauth_verifier);
				   		oauth.setOauth_token(token);
				   		
				   		String clientIp = Configuration.wifiIp;
				   			
				   		try {
				   			oauth = auth.accessToken(oauth);
				   		} catch (Exception e) {}
	
				   		if (oauth.getStatus() == 2) {
				   			System.out.println("Get Access Token failed!");
				   			return;
				   		} else { 
				   			ShareConstant.token = oauth.getOauth_token();
							ShareConstant.tokenSecret= oauth.getOauth_token_secret();
				   			TokenStore.store(this, ShareConstant.SHARE_TENCNT, oauth.getOauth_token(),
				   					oauth.getOauth_token_secret());
				   			Intent i=new Intent();
					        i.setClass(this, ShareDialog.class);
					        this.startActivityForResult(i, 3);
				   		}
			      }
 	         }   
		 }	       
		 
	 public static OAuth oauth;
	 public static OAuthClient auth ; 
	 
	 public void qqOauth(){
		 try {
			   oauth= new OAuth("OAuth://QWeiboShengYiJie"); // 初始化OAuth请求令牌	
		       auth = new OAuthClient();// OAuth 认证对象
			   oauth.setOauth_consumer_key(ShareConstant.TENCENTWEIBO_API_KEY);
			   oauth.setOauth_consumer_secret(ShareConstant.TENCENTWEIBO_API_SECRET);
			   
			   String[] oauth_token_array = TokenStore.fetch(this,ShareConstant.share_type);
			   ShareConstant.token = oauth_token_array[0];
			   ShareConstant.tokenSecret= oauth_token_array[1];
			   if(ShareConstant.token != null && ShareConstant.tokenSecret != null){
				    Intent i=new Intent();
			        i.setClass(this, ShareDialog.class);
			        this.startActivityForResult(i, 3);
			   }else{  
				    task=new Task();
				    task.execute(TASK_OAUTH_TENCENT); 
				 
			   } 
			}catch (Exception e) { }	 
	 }
	 
	 private AlertBox mypDialog; 
	 private final static int ALERT_LOADING=2;
	 
	 private final static int RESULT_OAUTH_SINA_OK=3;
	 private final static int RESULT_OAUTH_FAIL=4;
	 
	 private final static int RESULT_OAUTH_TENCENT_OK=5;
	 
	 //private final static String TASK_OAUTH_RENREN="renren"; 
	 private final static String TASK_OAUTH_SINA="sina"; 
	 private final static String TASK_OAUTH_TENCENT="tencent"; 
	 private final Handler handler = new Handler(Looper.getMainLooper()) {

			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {
				   case ALERT_LOADING:
					    mypDialog.setNoticeMessage("正在请求认证...");
					    mypDialog.show();
					    break;
				   case RESULT_OAUTH_SINA_OK:
					     try{
					        mypDialog.dismiss(); 
					        Intent i=new Intent();
							i.putExtra("uri", url);
							i.putExtra("type", ShareConstant.share_type);
							i.setClass(ShareSelectActivity.this, ShareLogin.class);
							ShareSelectActivity.this.startActivityForResult(i, 1); 
					     }catch(Exception e){}
					     break;
				   case RESULT_OAUTH_TENCENT_OK:
					     try{
					        mypDialog.dismiss();  
					        Intent intent=new Intent();
							intent.setClass(ShareSelectActivity.this, ShareLogin.class);
						    intent.putExtra("uri",url);
						    intent.putExtra("type",ShareConstant.SHARE_TENCNT); 
						    ShareSelectActivity.this.startActivityForResult(intent,1); 
					     }catch(Exception e){}
					     break;
				   case RESULT_OAUTH_FAIL:
					     try{
					       mypDialog.dismiss(); 
					       Toast.makeText(ShareSelectActivity.this, "请求登录认证失败。", Toast.LENGTH_SHORT).show();
					     }catch(Exception e){}
					     break;
                    
				}
			}
		};
 
		private class Task extends AsyncTask<String, String, String> {
 
			@Override
			protected String doInBackground(String... params) {
				if(params[0].equals(TASK_OAUTH_SINA)){
					return getSinaRequestToken();
				}else if(params[0].equals(TASK_OAUTH_TENCENT)){
					return getTencentRequestToken();
				}else{
					return "";
				}
			}
			 
			@Override
			protected void onPostExecute(String result) {				
				super.onPostExecute(result);

				if(result.equals("fail")){
					Message msg = Message.obtain();
					msg.what = RESULT_OAUTH_FAIL;
					handler.sendMessage(msg);
				}else if(result.equals("sina_success")){
					Message msg = Message.obtain();
					msg.what = RESULT_OAUTH_SINA_OK;
					handler.sendMessage(msg);
				}
				else if(result.equals("tencent_success")){
					Message msg = Message.obtain();
					msg.what = RESULT_OAUTH_TENCENT_OK;
					handler.sendMessage(msg);
				}
				
			}
 
			@Override
			protected void onPreExecute() { 
				super.onPreExecute(); 
				Message msg = Message.obtain();
				msg.what = ALERT_LOADING;
				handler.sendMessage(msg);
			}
 
			@Override
			protected void onProgressUpdate(String... values) {
				super.onProgressUpdate(values);

			}

		}
}
